/**
 * 留言管理
 */
var pageCurr;
var form;
$(function() {
    layui.use('table', function(){
        var table = layui.table;
        form = layui.form;

        tableIns=table.render({
            elem: '#boardList',
            url:'/board/getBoardList',
            method: 'post', //默认：get请求
            cellMinWidth: 80,
            page: true,
            request: {
                pageName: 'pageNum', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response:{
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 200, //成功的状态码，默认：0
                countName: 'totals', //数据总数的字段名称，默认：count
                dataName: 'list' //数据列表的字段名称，默认：data
            },
            cols: [[
                 {type:'numbers'}
                ,{field:'buyerOpenid', title:'Openid',align:'center'}
                ,{field:'userNickname', title:'用户名',align:'center'}
                ,{field:'userMessages', title:'留言',align:'center'}
                ,{field:'reply', title:'答复',align:'center'}
                ,{field:'createTime5', title: '创建时间',align:'center'}
                ,{field:'updateTime5', title: '更新时间',align:'center'}
                ,{field:'boardLabel', title: '用户是否已读',align:'center'}
                ,{field:'boardStatus', title: '客服是否已读',align:'center'}
                ,{title:'操作',align:'center', toolbar:'#optBar'}
            ]],
            done: function(res, curr, count){
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                //console.log(res);
                //得到当前页码
                console.log(curr);
                $("[data-field='boardLabel']").children().each(function(){
                    if($(this).text()=='0'){
                        $(this).text("未读")
                    }else if($(this).text()=='1'){
                        $(this).text("已读")
                    }
                });
                $("[data-field='boardStatus']").children().each(function(){
                    if($(this).text()=='0'){
                        $(this).text("未读")
                    }else if($(this).text()=='1'){
                        $(this).text("已读")
                    }
                });
                //得到数据总量
                //console.log(count);
                pageCurr=curr;
            }
        });

        //监听工具条
        table.on('tool(boardTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                //删除
                delBoard(data,data.boardId);
            } else if(obj.event === 'edit'){
                //编辑
                openBoard(data,"答复用户");
            }else if(obj.event === 'recover'){
                //恢复
                recoverBoard(data,data.boardId);
            }
        });

        //监听提交
        form.on('submit(boardSubmit)', function(data){
            // TODO 校验
            formSubmit(data);
            return false;
        });
    });

    //搜索框
    layui.use(['form','laydate'], function(){
        var form = layui.form ,layer = layui.layer
            ,laydate = layui.laydate;
        ///////
       var src='<option value="">请选择...</option>';
        $.ajax({
            url:'/board/getBoardStatus',
            type:'get',
            dataType:'json',
            async: true,
            success:function(data){
                $.each(data,function(index,item){
                    if(!boardStatus){
                        var option = new Option(item.name,item.boardStatus);
                    }else {
                        var option = new Option(item.name,item.boardStatus);
                        // // 如果是之前的parentId则设置选中
                        if(item.boardStatus == boardStatus) {
                            option.setAttribute("selected",'true');
                        }
                    }
                    $('#boardStatus').append(option);//往下拉菜单里添加元素
                    form.render('select'); //这个很重要
                })
            }
        });
        ////////
        //TODO 数据校验
        //监听搜索框
        form.on('submit(searchSubmit)', function(data){
            //重新加载table
           // $.post("/board/getBoardList",{"boardStatus":boardStatus},function(data){})
            //form.render();


            load(data);
            return false;
        });
    });


    /////////////////////////talk
   /* layui.use('table', function() {
        var table = layui.table;
        form = layui.form;
        tableInsTalk = table.render({
            elem: '#talkList',
            url: '/talk/getTalkList',
            method: 'post', //默认：get请求
            cellMinWidth: 80,
            page: true,
            request: {
                pageName: 'pageNum', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response: {
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 200, //成功的状态码，默认：0
                countName: 'totals', //数据总数的字段名称，默认：count
                dataName: 'list' //数据列表的字段名称，默认：data
            },
            cols: [[
                {type: 'numbers'}
                , {field: 'talkId', title: '文章编号', align: 'center'}
                , {field: 'buyerOpenid', title: '用户编号', align: 'center'}
                , {field: 'userNickname', title: '作者', align: 'center'}
                , {field: 'title', title: '标题', align: 'center'}
                , {field: 'talkText', title: '文章', align: 'center'}
                , {field: 'createTime', title: '创建时间', align: 'center'}
                , {field: 'updateTime', title: '更新时间', align: 'center'}
                , {field: 'picture', title: '图片', align: 'center',
                    templet: function(data) {
                        //return  "<img src='"+datum.formatUrl(d.url)+"' style='height:50px;'";
                        //////
                        if(data.picture!=null&&data.picture!="null"){
                        ///////图片展示
                        var i=0;
                        var picture=[];
                        var url = [];
                        var str="";
                        var pictureUrl = data.picture.split(",");
                        for (var j in pictureUrl) {
                            picture[i] = pictureUrl[j].split("/");


                            if (picture[i] != null) {
                                url[i] = "http://localhost:8080/" +picture[i][picture[i].length - 2]+"/"+ picture[i][picture[i].length - 1];
                            }
                            str+= '<a href="' + url[i] + '" target="_blank " title="点击查看">' +
                                '<img src="' + url[i] + '" style="height:30px;" />' +
                                '</a>';
                            i=i+1;
                        }
                            return str;
                        }
                    }
                }

                , {field: 'houtaiStatus', title: '文章状态', align: 'center'}
                , {title: '操作', align: 'center', toolbar: '#optBar0'}
            ]],
            done: function (res, curr, count) {
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                //console.log(res);
                //得到当前页码
                console.log(curr);

                $("[data-field='houtaiStatus']").children().each(function () {
                    if ($(this).text() == '0') {
                        $(this).text("有效")
                    } else if ($(this).text() == '1') {
                        $(this).text("无效")
                    }
                });
                //得到数据总量
                //console.log(count);
                pageCurr = curr;
            }
        });

        //监听工具条
        table.on('tool(talkTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'deleteTalk') {
                //删除
                delTalk(data, data.talkId);
            } else if (obj.event === 'seeTalk') {
                //编辑
                openTalk(data, "查看文章详情");
            }
        });

    });*/

    /////////////////////结束
});
/*
///////////////////////talk方法
function openTalk(data,title){
    if(data==null || data==""){
        $("#talkId").val("");
    }else{
        $("#talkId").val(data.talkId);
        $("#userNickname").val(data.userNickname);
        $("#title").val(data.title);
        $("#talkText").val(data.talkText);
        $("#picture").val(data.picture);

    }
    var pageNum = $(".layui-laypage-skip").find("input").val();
    $("#pageNum").val(pageNum);


    layer.open({
        type:1,
        title: title,
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['550px'],
        content:$('#setTalk'),
        end:function(){
            cleanTalk();
        }
    });
}

function delTalk(obj,talkId) {
    if(null!=talkId){
        layer.confirm('删除该内容？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/talk/updateTalkStatus",{"talkId":talkId,"houtaiStatus":1},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(){
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.closeAll();
        });
    }
}*/


//////////talk结束

//提交表单
function formSubmit(obj){
    $.ajax({
        type: "POST",
        data: $("#boardForm").serialize(),
        url: "/board/setBoard",
        success: function (data) {
            if (data.code == 1) {
                layer.alert(data.msg,function(){
                    layer.closeAll();
                    load(obj);
                });
            } else {
                layer.alert(data.msg);
            }
        },
        error: function () {
            layer.alert("操作请求错误，请您稍后再试",function(){
                layer.closeAll();
                //加载load方法
                load(obj);//自定义
            });
        }
    });
}


function openBoard(data,title){
    if(data==null || data==""){
        $("#boardId").val("");
    }else{
        $("#boardId").val(data.boardId);
        $("#userNickname").val(data.userNickname);
        $("#userMessages").val(data.userMessages);
        $("#reply").val(data.reply);

    }
    var pageNum = $(".layui-laypage-skip").find("input").val();
    $("#pageNum").val(pageNum);


    layer.open({
        type:1,
        title: title,
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['550px'],
        content:$('#setBoard'),
        end:function(){
            cleanBoard();
        }
    });
}

function delBoard(obj,boardId) {
    if(null!=boardId){
        layer.confirm('该信息设置为已读？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/board/updateBoardStatus",{"boardId":boardId,"boardStatus":1},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(){
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.closeAll();
        });
    }
}
//恢复
function  recoverBoard(obj,boardId) {
    if(null!=boardId){
        layer.confirm('该信息设置为未读？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/board/updateBoardStatus",{"boardId":boardId,"boardStatus":0},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(){
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.closeAll();
        });
    }
}

function load(obj){
    //重新加载table
    tableIns.reload({
        where: obj.field
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });
    //重新加载table
    /*tableInsTalk.reload({
        where: obj.field
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });*/

}

function cleanBoard(){

    $("#reply").val("");

}
